﻿using OpenTK.Graphics.OpenGL;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NinjaGoat
{
    class Texture
    {
        int id;
        int width, height;

        public void Load(string path)
        {
            using(Bitmap image = new Bitmap(path))
                SetData(image);
        }
        public void SetData(Bitmap image)
        {
            image.RotateFlip(RotateFlipType.RotateNoneFlipY);

            OpenTK.Graphics.OpenGL.PixelFormat dataFormat;
            OpenTK.Graphics.OpenGL.PixelInternalFormat textureFormat;

            switch (image.PixelFormat)
            {
                case System.Drawing.Imaging.PixelFormat.Format24bppRgb:
                    dataFormat = OpenTK.Graphics.OpenGL.PixelFormat.Bgr;
                    textureFormat = PixelInternalFormat.Rgb;
                    break;
                case System.Drawing.Imaging.PixelFormat.Format32bppRgb:
                case System.Drawing.Imaging.PixelFormat.Format32bppArgb:
                    dataFormat = OpenTK.Graphics.OpenGL.PixelFormat.Bgra;
                    textureFormat = PixelInternalFormat.Rgba;
                    break;
                default:
                    throw new NotImplementedException("Pixel format \"" + image.PixelFormat.ToString() + "\" not supported yet");
            }
            System.Drawing.Imaging.BitmapData imageData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, image.PixelFormat);

            width = imageData.Width;
            height = imageData.Height;

            id = GL.GenTexture();
            GL.BindTexture(TextureTarget.Texture2D, id);
            GL.TexImage2D(TextureTarget.Texture2D, 0, textureFormat, imageData.Width, imageData.Height, 0,
                dataFormat, PixelType.UnsignedByte, imageData.Scan0);
            image.UnlockBits(imageData);

            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear);

            ErrorCode e = GL.GetError();
            if (e != ErrorCode.NoError)
                throw new Exception("OpenGL Error");
        }

        public void Bind()
        {
            GL.BindTexture(TextureTarget.Texture2D, id);
        }
    }
}
